Programming Questions for Practice
Write a method that, given a positive integer number, returns the smallest number with the same number of digits.
For instance, given N=4751, the method returns 1000. Given N=100, the method should return 100. Given N=1, the method should return 0.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
Write a method that, given a positive integer number,
returns the smallest number with the same number of digits.
For instance, given N=4751, the method returns 1000.
Given N=100, the method should return 100.
Given N=1, the method should return 0.
*/
int digitsCount(int number) {
int count = 0;
while(number > 0) {
count++;
number /= 10;
}
return count;
}
int findSmallest(int number) {
int smallestNumber = 0;
int length = digitsCount(number);
if(number <= 1 || length == 1)
return smallestNumber;
else {
return (int)pow(10, length-1);
}
}
int main()
{
int number;
printf("Enter any number: ");
scanf("%d", &number);
printf("Smallest number with same number of digits: %d\n", findSmallest(number));
return 0;
}
import java.util.Scanner;
/*
Write a method that, given a positive integer number,
returns the smallest number with the same number of digits.
For instance, given N=4751, the method returns 1000.
Given N=100, the method should return 100.
Given N=1, the method should return 0.
*/
public class SmallestEqualDigitsNumber {
public static int findSmallest(int number) {
int smallestNumber = 0;
if(number <= 0 || String.valueOf(number).length() == 1)
return smallestNumber;
else
return (int)Math.pow(10, String.valueOf(number).length()-1);
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = read.nextInt();
System.out.println("Smallest number with same number of digits: " + findSmallest(number));
read.close();
}
}
Code not available...